package cn.com.nes.site.service.system.dict.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.mybatis.agent.system.entity.TParam;
import cn.com.nes.mybatis.agent.system.mapper.TParamMapper;
import cn.com.nes.site.entity.em.system.DictTypeEnum;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典服务
 */
@Service
public class TParamServiceImpl extends ServiceImpl<TParamMapper, TParam> implements TParamService {

    @Override
    public String getNameByParamTypeAndValue(String paramType, String value) {
        if (StrUtil.isBlank(paramType) || StrUtil.isBlank(value)) {
            return StrUtil.EMPTY;
        }
        String name = this.baseMapper.getNameByParamTypeAndValue(paramType, value);
        if (StrUtil.isBlank(name)) {
            return StrUtil.EMPTY;
        }
        return name;
    }


    /**
     * 查询字典列表
     * @param paramType 字典类型
     */
    @Override
    public List<TParam> getList(String paramType) throws Exception {
        return this.baseMapper.selectList(new QueryWrapper<TParam>().eq("is_delete", 0).eq("param_type", paramType));
    }

    /**
     * 字典Map
     * 格式：<value, param>
     * @param paramType 字典类型
     */
    @Override
    public Map<String, TParam> getMapValueIsKey(String paramType) throws Exception {
        List<TParam> list = this.getList(paramType);
        if (CollUtil.isEmpty(list)) {
            return MapUtil.empty();
        }
        return list.stream().collect(Collectors.toMap(TParam::getValue, param -> param));
    }

    /**
     * list 转 Map， 必须是同一类别的字典
     *  格式：<TParam::value, TParam>
     * @param list 字典列表
     */
    @Override
    public Map<String, TParam> convertToMapForSameType(List<TParam> list) throws Exception {
        if (CollUtil.isEmpty(list)) {
            return MapUtil.empty();
        }
        Set<String> sets = list.stream().map(TParam::getParamType).collect(Collectors.toSet());
        if (sets.size() > 1) {
            throw new IllegalBusinessException("不是同一类型字典，不能转换！");
        }
        return list.stream().collect(Collectors.toMap(TParam::getValue, param -> param));
    }

    @Override
    public List<Map<String, String>> getListMap(String paramType) throws Exception {
        List<TParam> paramList = this.getList(paramType);
        if (CollUtil.isEmpty(paramList)) {
            return ListUtil.empty();
        }
        List<Map<String, String>> list = new ArrayList<>();
        paramList.forEach(item -> {
            Map<String, String> map = new HashMap<>();
            map.put("value", item.getValue());
            map.put("name", item.getName());
            list.add(map);
        });
        return list;
    }

    @Override
    public String getValueByName(String paramType, String name) {
        QueryWrapper<TParam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("param_type", paramType);
        queryWrapper.eq("is_delete", false);

        List<TParam> tParams = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(tParams)) {
            for (TParam tParam : tParams) {
                if (tParam.getName().equals(name)) {
                    return tParam.getValue();
                }
            }
        }

        // value值设定规则：如果是字符串就随机,如果是数值就自增
        boolean isNumber = true;
        int maxValue = Integer.MIN_VALUE;
        for (TParam tParam : tParams) {
            try {
                // 寻找最大的value,同时将value转换为数值，如果异常就说明是字符串
                int intValue = Integer.parseInt(tParam.getValue());
                if (intValue > maxValue) {
                    maxValue = intValue;
                }
            } catch (Exception e) {
                isNumber = false;
                break;
            }
        }

        // 如果没查询到就新增
        TParam tParam = new TParam();
        tParam.setParamType(paramType);
        tParam.setTypeName(DictTypeEnum.getTypeName(paramType));
        tParam.setName(name);
        tParam.setValue(isNumber ? String.valueOf(++maxValue) : UUID.randomUUID().toString().replace("-", "").substring(0, 15));
        tParam.setIsDelete(0);
        tParam.setSort(0);
        tParam.setGmtCreate(new Date());

        try {
            int rows = this.baseMapper.insert(tParam);
            if (rows != 1) {
                return tParam.getValue();
            }
        } catch (Exception e) {
            return tParam.getValue();
        }
        return tParam.getValue();
    }

}
